/**
 * IP 검색관련 Class
 * 
 * @author KJH
 * @version 1.0, 2012-03-08 
 * @fix([수정자]) [yyyy-mm-dd]: [수정 내용]
 *
 */

package com.ubst.smartad.common;

import java.util.*;
import java.io.*;

// BinaryTree를 이용한 트리검색으로 빠른검색속도를 자랑한다.
public class IpSearcher implements Serializable{
	BinaryTree top;

	public IpSearcher() {
		top = new BinaryTree();
	}

	public void put(byte[] value) {
		BinaryTree cur = top;
		int i;

		for(i=0; i<value.length; i++) {
			if(cur.getValue() == (byte)0x00) {
				if(value[i] == '*'){
					cur.setValue2(value[i]);
				}else {
					cur.setValue(value[i]);
					cur.addLeft(new BinaryTree());
					cur = cur.getLeft();
				}
			}else {
				if(value[i] == '*') {
					cur.setValue2(value[i]);
					continue;
				}

				while(cur.getValue() != value[i] && cur.getRight() != null){	/* search on brother */
					cur = cur.getRight();
				}

				if(cur.getValue() == value[i]) {	/* found same character */
					if(cur.getLeft() == null) {
						cur.addLeft(new BinaryTree());
						cur = cur.getLeft();
					}else{
						cur = cur.getLeft();
					}
				}else if(cur.getRight() == null) {	/* Not found same character */
					cur.addRight(new BinaryTree(value[i]));
					cur = cur.getRight();

					cur.addLeft(new BinaryTree());
					cur = cur.getLeft();
				}
			} 	/* if(cur.getValue() != null */
		} // end for
	}

	public void put(String value) {
		this.put(value.getBytes());
	}

	public boolean is(byte[] value) {
		BinaryTree cur = top;

		if(cur.getValue() == (byte)0x00){
			return false;
		}

		for(int i=0; i<value.length; i++) {
			while(cur.getValue() != value[i] && cur.getRight() != null)	{ /* search on brother */
			cur = cur.getRight();
		}

		if(cur.getValue() == value[i]) {  /* found same character */
			if(cur.getLeft() == null){
				return false;
			}else {
				cur = cur.getLeft();
				if(cur.getValue2() == '*'){
					return true;
				}
			}
		}else if(cur.getRight() == null) 	/* Not found same character */
			return false;
		}

		if(cur == top){
			return false;
		}else if(cur.getValue() == (byte)0x00){
			return true;
		}else{
			return false;
		}
	}

	public boolean is(String value) {
		return this.is(value.getBytes());
	}

}
